package com.t235.gc.auth.security;

import com.t235.gc.dao.SysManagerDao;
import com.t235.gc.dao.SysRoleDao;
import com.t235.gc.entity.SysManager;
import com.t235.gc.entity.SysRole;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GcManagerService implements UserDetailsService {
    @Resource
    private SysManagerDao sysManagerDao;
    @Resource
    private SysRoleDao sysRoleDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysManager sysManager = new SysManager();
        sysManager.setUseraccount(username);
        List<SysManager> list = sysManagerDao.queryAll(sysManager);
        if(list == null || list.isEmpty()) {
            throw new UsernameNotFoundException("账号不存在" + username);
        }
        SysManager manager = list.get(0);
        List<SysRole> roles = sysRoleDao.queryByManagerId(manager.getManagerid());
        return new User(manager.getUseraccount(), manager.getPassword(), manager.getIsflag() == 2,true, true, true,
                roles.stream().map(sysRole -> new SimpleGrantedAuthority(sysRole.getRolename())).collect(Collectors.toList()));
    }
}
